/*-------执行SQLite注入,数据库的基本操作(Begin)-------*/
(function($N){
    var db = {};
    function sqlErrorHandler(tx, error) {
       console.log("database operation failed error: " + error.message);
    }
    
    function createTableWithPrimaryKey(tableName, fields,id, callBack) {
        var sql = "CREATE TABLE IF NOT EXISTS " + tableName + "( " + id + " integer primary key autoincrement,";

            // 合并字段串同时去除传入的主键字段
            sql += fields.join(",") + ")";
            console.log(sql);

            this.db.transaction(function (tx) {
                tx.executeSql(sql, [], function () {
                    if (callBack) callBack();
            }, sqlErrorHandler);
        })
    }
    
    function createNormalTable(tableName, fields, callBack){
        var sql = "CREATE TABLE IF NOT EXISTS " + tableName + "( ";

        // 合并字段串同时去除传入的主键字段
        sql += fields.join(",") + ")";
        console.log(sql);

        this.db.transaction(function (tx) {
            tx.executeSql(sql, [], function () {
                if (callBack) callBack();
            }, sqlErrorHandler);
        });
    }
    
    function dropTable(tableName, callback){
        var sql = "DROP TABLE " + tableName;
        this.db.transaction(function (tx) {
            tx.executeSql(sql,callback, sqlErrorHandler);
        });
    }
    
    function executeSQL(db, sqlCommand, valueArray, successCallback, failCallback) {
        console.log("sqlCommand = " + sqlCommand);
        db.transaction(function(tx) {
            tx.executeSql(sqlCommand,valueArray, function(tx, result){
                if(typeof(successCallback) === "function" ){
                    successCallback(tx, result);
                } else if(typeof(successCallback) !== "undefined"){
                    successCallback.cb(tx, result, successCallback.data);
                }
            }, failCallback || sqlErrorHandler);
        });
    }
    
    function SQLProvider(dbName, size) {
        this.dbName = dbName || 'MyTestDatabase';
        var db = openDatabase(this.dbName, '1.0', 'database for ' + this.dbName, (size || 2) * 1024 * 1024);
        this.db = db;
        /*create tables*/
        this.createTableWithPrimaryKey = createTableWithPrimaryKey;
        this.createNormalTable = createNormalTable;
        
        /*execute SQL*/
        this.executeSQL = executeSQL; 
        /*drop tables*/
        this.dropTable = dropTable;
        
    }
    
    $N.databaseSet = new SQLProvider();
}($N || {}));



